<template>
    <div class="table_add">
        <div class="header">
            <el-form ref="TableFormRef" :model="state.table" :rules="state.tableRules">
                <el-form-item prop="name">
                    <el-input v-model="state.table.name" placeholder="请输入报表名称" size="large" clearable
                        style="width:300px" />
                </el-form-item>
            </el-form>
            <div class="add">
                <el-button type="primary" @click="toAddColumn">新增</el-button>
                <el-button type="primary" @click="handleDel">删除</el-button>
            </div>
        </div>
        <el-divider content-position="left">报表字段</el-divider>
        <div class="content">
            <div class="tabs">
                <div class="tab " v-for="(item, index) in state.table.columns" :key="item.uuid"
                    @click="tabClick(item, index)" :class="[state.active_tab_idx == index ? 'tab_active' : '']">
                    {{ item.name }}
                </div>
            </div>
        </div>
        <el-divider content-position="left">操作区</el-divider>
        <div class="footer">
            <el-form ref="FormRef" :model="handleForm" label-width="auto" :rules="state.rules"
                v-if="state.active_tab_idx != null">
                <el-form-item label="字段名称" prop="name">
                    <el-input v-model="handleForm.name" style="max-width: 400px" />
                </el-form-item>
                <el-form-item label="字段类型" prop="fieldType">
                    <el-select v-model="handleForm.fieldType" value-key="code" placeholder="请选择字段类型"
                        @change="handleTypeChange" style="max-width: 400px">
                        <el-option v-for="item in state.fieldTypes" :key="item.code" :label="item.des" :value="item">
                            <span>{{ item.des }}</span>
                            <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
                                {{ item.remark }}
                            </span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="字段序号" prop="sort">
                    <el-input-number v-model="handleForm.sort" :min="1" :max="255"
                        @change="(currentValue, oldValue) => handleSortChange(currentValue, handleForm.uuid)" />
                    <span class="field_rremark">字段在表格中的序号</span>
                </el-form-item>
                <el-form-item label="是否必填" prop="required">
                    <el-switch v-model="handleForm.required" />
                    <span class="field_rremark">该字段在用户录入的时候是否必填项</span>
                </el-form-item>
                <el-form-item label="字段长度" prop="sort" v-if="handleForm.fieldType?.isSetLength">
                    <el-input-number v-model="handleForm.len" :min="handleForm.minLen" :max="handleForm.maxLen" />
                    <span class="field_rremark">字段的长度，文本类型为该字段录入的最大字符数量，小数类型为(整数位+小数位)个数</span>
                </el-form-item>
                <el-form-item label="小数位" prop="sort" v-if="handleForm.fieldType?.isSetAccuracy">
                    <el-input-number v-model="handleForm.accuracy" :min="handleForm.minAccuracy"
                        :max="handleForm.maxAccuracy" @change="handleAccuracyChange" />
                    <span class="field_rremark">字段的小数位个数</span>
                </el-form-item>

            </el-form>
        </div>
        <div class="submit">
            <el-button type="primary" @click="submit">提交</el-button>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, computed, nextTick, onMounted } from "vue"
import { fieldTypeEnums } from '@/api/common/common'
import { add } from '@/api/enact/table'
import { v4 as uuidv4 } from 'uuid';
import { ElMessage } from 'element-plus'
import router from "@/router";


const TableFormRef = ref(null)
const FormRef = ref(null)
const state = reactive({
    active_tab_idx: undefined,
    fieldTypes: [],
    maxSort: 0,
    table: {
        name: undefined,
        columns: []
    },
    tableRules: {
        name: [
            { required: true, message: '报表名称不能为空', trigger: 'blur' },
            { min: 2, max: 50, message: '报表名称为1-50个字符', trigger: 'blur' },
        ],
    },
    rules: {
        name: [
            { required: true, message: '字段名称不能为空', trigger: 'blur' },
            { min: 1, max: 10, message: '字段名称为1-10个字符', trigger: 'blur' },
        ],
        fieldType: [
            {
                required: true,
                message: '请选择字段类型',
                trigger: 'change',
            },
        ]
    }
})

const handleForm = computed(() => {
    if (state.active_tab_idx == null) {
        return null
    }
    return state.table.columns[state.active_tab_idx]
})


const tabClick = async (item, index) => {
    await FormRef.value.validate((valid, fields) => {
        if (valid) {
            state.active_tab_idx = index
        }
    })
}

const toAddColumn = async () => {
    if (state.active_tab_idx == null) {
        doAddColumn()
    } else {
        await FormRef.value.validate((valid, fields) => {
            if (valid) {
                doAddColumn()
            }
        })
    }

}
const doAddColumn = () => {
    let sort = state.maxSort + 1
    state.table.columns.push({
        uuid: uuidv4(),
        name: undefined,
        fieldType: undefined,
        sort: sort,
        required: true,
    })
    state.active_tab_idx = state.table.columns.length - 1
    state.maxSort = sort
}


const handleSortChange = (currentValue, uuid) => {
    if (currentValue > state.maxSort) {
        state.maxSort = currentValue
    }
    state.table.columns.sort((a, b) => a.sort - b.sort)
    for (let i = 0; i < state.table.columns.length; i++) {
        const item = state.table.columns[i];
        if (item.uuid == uuid) {
            state.active_tab_idx = i
        }
    }
}

const handleTypeChange = (val) => {
    if (val.isSetLength) {
        state.table.columns[state.active_tab_idx].len = val.defaultLength
        state.table.columns[state.active_tab_idx].minLen = val.minLength
        state.table.columns[state.active_tab_idx].maxLen = val.maxLength
    }
    if (val.isSetAccuracy) {
        state.table.columns[state.active_tab_idx].accuracy = val.defaultAccuracy
        state.table.columns[state.active_tab_idx].minAccuracy = val.minAccuracy
        state.table.columns[state.active_tab_idx].maxAccuracy = val.maxAccuracy
    }
}

const handleAccuracyChange = (currentValue) => {
    if (state.table.columns[state.active_tab_idx].len < (currentValue + 1)) {
        state.table.columns[state.active_tab_idx].len = currentValue + 1
    }
    state.table.columns[state.active_tab_idx].minLen = currentValue + 1
}

const handleDel = () => {
    if (state.active_tab_idx != null) {
        state.table.columns.splice(state.active_tab_idx, 1)
        state.active_tab_idx = state.table.columns.length - 1
    }
}

const submit = async () => {
    await TableFormRef.value.validate(async (valid, fields) => {
        if (!valid) {
            return
        }
        if (!state.table.columns || state.table.columns.length == 0) {
            ElMessage.error('请添加报表字段.')
            return
        }
        await FormRef.value.validate((valid, fields) => {
            if (!valid) {
                return
            }
            add(state.table).then(data => {
                router.push("/table-list")
            })

        })
    })
}
const getFieldType = () => {
    fieldTypeEnums().then(data => {
        state.fieldTypes = data
    })
}

onMounted(() => {
    getFieldType()
})


</script>
<style scoped lang="scss">
.table_add {
    height: 100%;
    display: flex;
    flex-direction: column;

    .header {
        height: 60px;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;

        :deep(.el-form-item) {
            margin-bottom: 0;
        }

        .add {
            position: absolute;
            right: 20px;
            bottom: -10px;
        }

    }

    .content {
        height: 80px;

        .tabs {
            height: 100%;
            display: flex;
            align-items: center;
            padding: 0 20px;

            .tab:not(:first-child) {
                margin-left: 5px;
            }

            .tab {
                padding: 3px 10px;
                background: #ffffff;
                border: 1px solid #dcdfe6;
                color: #606266;
                min-width: 100px;
                border-radius: 4px;
                cursor: pointer;
            }

            .tab_active {
                background: rgb(236, 245, 255);
                color: #409eff;
                border: 1px solid rgb(217, 236, 255);
            }
        }
    }

    .footer {
        flex-grow: 1;
        flex-shrink: 0;
        padding: 0 20px;

        .field_rremark {
            font-size: 13px;
            color: #9e9e9e;
            margin-left: 10px;
        }
    }

    .submit {
        padding: 0 20px;
        height: 50px;
        flex-shrink: 0;
    }
}
</style>
